import { app } from "../../../scripts/app.js";
import { ComfyDialog, $el } from "../../../scripts/ui.js";

// LoRA管理器模态框类
class LoraManagerModal extends ComfyDialog {
    static instance = null;

    static getInstance() {
        if (!LoraManagerModal.instance) {
            LoraManagerModal.instance = new LoraManagerModal();
        }
        return LoraManagerModal.instance;
    }

    constructor() {
        super();
        this.modalElement = null;
        this.iframeElement = null;
        this.iframeWrapper = null;
        this.isLayoutInitialized = false;
    }

    buildButtons() {
        return [];
    }

    createButton(label, onClick) {
        const buttonElem = document.createElement("button");
        buttonElem.classList.add("lora-btn");
        buttonElem.innerText = label;
        buttonElem.addEventListener("click", onClick);
        return buttonElem;
    }

    layoutModal() {
        const self = this;

        const footerPanel = document.createElement("div");
        footerPanel.classList.add("footer-panel");
        this.modalElement.appendChild(footerPanel);

        const cancelBtn = this.createButton("关闭", () => {
            self.close();
        });
        cancelBtn.classList.add("lora-cancel-btn");

        footerPanel.appendChild(cancelBtn);
    }

    show() {
        if (this.modalElement) {
            document.body.removeChild(this.modalElement);
        }

        this.modalElement = $el("div.comfy-modal", { parent: document.body }, [
            $el("div.comfy-modal-content", [...this.buildButtons()])
        ]);

        if (!this.isLayoutInitialized) {
            this.layoutModal();
            this.isLayoutInitialized = true;
        }

        this.iframeElement = $el("iframe", {
            src: "/xhh/lora-manager",
            style: { border: "none", width: "100%", height: "100%" },
        });

        this.iframeWrapper = document.createElement("div");
        this.iframeWrapper.classList.add("iframe-wrapper");
        this.modalElement.appendChild(this.iframeWrapper);
        this.modalElement.classList.add("comfy-modal-layout");
        this.iframeWrapper.appendChild(this.iframeElement);

        // 监听来自LoRA管理器的消息
        window.addEventListener("message", (event) => {
            console.log("🎯 LoRA管理器收到消息:", event.data);
            
            if (event.data.type === "use_lora") {
                console.log("🎯 收到use_lora消息，LoRA信息:", event.data);
                
                // 查找所有XHH_LoraSeletorDisplay节点
                const loraNodes = app.graph._nodes.filter(node => node.type === "XHH_LoraSeletorDisplay");
                console.log("🎯 找到所有LoRA节点:", loraNodes);
                
                if (loraNodes.length > 0) {
                    // 优先使用选中的节点，否则使用第一个
                    let targetNode = null;
                    if (app.canvas.selected_nodes && app.canvas.selected_nodes.length > 0) {
                        targetNode = loraNodes.find(node => app.canvas.selected_nodes.includes(node.id));
                    }
                    if (!targetNode) {
                        targetNode = loraNodes[0];
                    }
                    
                    console.log("🎯 目标节点:", targetNode);
                    
                    // 查找selected_lora输入widget
                    const selectedLoraWidget = targetNode.widgets.find(w => w.name === "selected_lora");
                    if (selectedLoraWidget) {
                        console.log("🎯 找到selected_lora widget:", selectedLoraWidget);
                        
                        // 更新widget的值
                        selectedLoraWidget.value = event.data.lora_path;
                        
                        // 调用widget的callback
                        if (selectedLoraWidget.callback) {
                            selectedLoraWidget.callback(event.data.lora_path);
                        }
                        
                        // 触发输入事件
                        if (selectedLoraWidget.inputEl) {
                            selectedLoraWidget.inputEl.value = event.data.lora_path;
                            selectedLoraWidget.inputEl.dispatchEvent(new Event('input', { bubbles: true }));
                            selectedLoraWidget.inputEl.dispatchEvent(new Event('change', { bubbles: true }));
                        }
                        
                        // 触发节点的onChange事件
                        if (targetNode.onChange) {
                            targetNode.onChange();
                        }
                        
                        console.log("✅ LoRA路径已更新到selected_lora:", event.data.lora_path);
                    } else {
                        console.log("❌ 未找到selected_lora widget");
                    }
                } else {
                    console.log("❌ 未找到任何XHH_LoraSeletorDisplay节点");
                }
                
                this.close();
            }
        });
    }

    close() {
        if (this.iframeWrapper) {
            this.modalElement.removeChild(this.iframeWrapper);
            this.iframeWrapper = null;
        }
        if (this.modalElement) {
            document.body.removeChild(this.modalElement);
            this.modalElement = null;
        }
        this.isLayoutInitialized = false;
        super.close();
    }
}

// LoRA管理器按钮扩展
app.registerExtension({
    name: "ComfyUI-xhh.lora_manager_button",
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        if (nodeData.name === "XHH_LoraSeletorDisplay") {
            console.log("🎯 注册LoRA管理器按钮扩展");
            
            // 重写onNodeCreated方法
            const originalNodeCreated = nodeType.prototype.onNodeCreated;
            nodeType.prototype.onNodeCreated = function() {
                const result = originalNodeCreated?.apply(this, arguments);
                
                // 添加LoRA管理器按钮
                const buttonWidget = this.addWidget("button", "LoRA Manager", "lora_manager", () => {
                    console.log("🎯 按钮被点击，准备打开LoRA管理器");
                    const modal = LoraManagerModal.getInstance();
                    modal.show();
                });
                
                console.log("🎯 按钮widget创建完成:", buttonWidget);
                
                console.log("✅ LoRA管理器按钮添加成功");
                return result;
            };
        }
    }
});

// 添加样式
const style = document.createElement("style");
style.innerHTML = `
    .comfy-modal-layout {
        display: flex;
        flex-direction: column;
        width: 90vw;
        height: 90vh;
        max-width: 100vw;
        max-height: 100vh;
        padding: 0;
        z-index: 8888;
    }
    .iframe-wrapper {
        flex: 1;
        padding-bottom: 40px;
        background: #474747;
    }
    .footer-panel {
        display: flex;
        justify-content: flex-end;
        position: absolute;
        bottom: 0;
        right: 0px;
        height: 38px;
    }
    .lora-btn {
        margin: 4px;
        padding-left: 16px;
        padding-right: 16px;
        background-color: #262627 !important;
        font-size: 14px !important;
    }
    .lora-cancel-btn {
        border-color: #482626 !important;
        background-color: #262627 !important;
        font-size: 14px !important;
        color: #ac7b7b !important;
    }
`;
document.head.appendChild(style);

export default {};
